package com.cheng.web.action.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cheng.bos.actionUtils.ActionUtils;
import com.cheng.domain.system.User;
import com.cheng.service.system.UserService;
import com.opensymphony.xwork2.ActionContext;

@Namespace("/user")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class UserAction extends ActionUtils<User> {
	
	@Autowired
	private UserService userService;

	@Action(value="login",results={@Result(name="login",type="redirect",location="../login.html"),@Result(name="success",type="redirect",location="../index.html")})
	public String login(){
		//创建shiro登录实例
		Subject subject = SecurityUtils.getSubject();
		//传递用户登录信息
		AuthenticationToken token = new UsernamePasswordToken(model.getUsername(),model.getPassword());
		//保存登录结果
		Map<String, Object> resault = new HashMap<>();
		//登录验证
		try {
			subject.login(token);
			return SUCCESS;
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			return LOGIN;
		}catch(IncorrectCredentialsException e){
			e.printStackTrace();
			return LOGIN;
		}
	}
	@Action(value="logout",results={@Result(name="success",type="redirect",location="../login.html")})
	public String logout(){
		// 基于shiro完成退出
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS;
	}
	
	@Action(value="user_query",results={@Result(name="success",type="json")})
	public String findAllUser(){
		List<User> list =userService.findAllUser();
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
	
	private Integer[] roleIds;

	public void setRoleIds(Integer[] roleIds) {
		this.roleIds = roleIds;
	}
	@Action(value="user_save",results={@Result(name="success",type="redirect",location="../pages/system/userlist.html")})
	public String saveUser(){
		userService.saveUser(model,roleIds);
		return SUCCESS;
	}
}
